<?php

namespace App\Eloqumd\System;

use Config;
use Hash;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Ramsey\Uuid\Uuid;
use App\Eloqumd\System\Plate;

class PlateUser extends Model
{
    public $timestamps = false;

    // 用户登录校验
    public static function userCheckOfSign($name, $pass)
    {
        if (!$originUserData = self::where('user_name', $name)->first()) {
            return ['status' => false, 'message' => trans('alg.The-User-Not-Exist')];
        }

        if (Hash::check($pass, $originUserData['user_pass'], ['solt' => $originUserData['user_solt']])) {
            // 判断平台是否被禁用
            // 关联平台信息
            $plateData = Plate::where('plate_code', $originUserData['user_plate'])->first();
            // 判断平台是否被禁用
            if (!$plateData['plate_status']) {
                return ['status' => false, 'message' => trans('alg.The-User-Plate-Has-Disabled')];
            }

            if (!$originUserData['user_status']) {
                return ['status' => false, 'message' => trans('alg.The-User-Has-Disabled')];
            }

            $userPwdCache = simple_encrypt($originUserData['user_pass'], 'E', Config::get('api.pwd_cache'));
            // 剔除安全隐患字段
            unset($originUserData['user_pass']);
            unset($originUserData['user_solt']);
            // 添加token字段
            $originUserData['token'] = Uuid::uuid1()->getHex();
            $plateData['plate_id'] = $plateData['id'];
            unset($plateData['id']);
            unset($plateData['plate_secret']);
            $originUserData = array_merge($originUserData->toArray(), $plateData->toArray());

            // 缓存设置，默认缓存登录一周
            $redisKey = $originUserData['id'] . '_' . $originUserData['token'];
            if ($loginCacheTtl = Config::get('api.login_cache')) {
                Redis::setex($redisKey, $loginCacheTtl, serialize($originUserData));
                Redis::setex($redisKey . '_ps', $loginCacheTtl, $userPwdCache);
            } else {
                Redis::set($redisKey, serialize($originUserData));
                Redis::set($redisKey . '_ps', $userPwdCache);
            }

            return ['status' => true, 'data' => $originUserData];
        }

        return ['status' => false, 'message' => trans('alg.Username-Or-Userpass-Error')];
    }
}
